<?php

namespace app\api\controller;

use app\common\controller\Api;
use fast\Http;
use think\Config;
/**
 * 首页接口
 */
class Index extends Api
{
    protected $noNeedLogin = '*';
    protected $noNeedRight = [];

    public function _initialize()
    {
        parent::_initialize();
        $this->CustomerCustomers=model('admin/customer/Customers');
        $this->department=model('admin/Department');
        $this->user=model('admin/User');
        $this->area=model('admin/Area');
    }

    /**
     * 基础信息
     *
     */
    public function index()
    {
        $data['name']=Config('site.name');
        $data['logo']=cdnurl(Config('site.logo'),true) ;

        $data['contact_mobile']=Config('site.contact_mobile');
        $data['agreement']=Config('site.agreement');
        $data['yinsi']=Config('site.yinsi');
        $data['about']=Config('site.about');
        $this->success('OK',$data);
    }

    public  function  areaList($pid=0){
     $this->success('OK',$this->area->where('pid',$pid)->select());
    }

    /**
     * 企业客户信息导入
     */
    /**
     * 导入客户列表
     */
    public  function customerList(){
        $result=getaccess_token();
        if ($result['ret']) {
            $json = (array)json_decode($result['msg'], true);
            $access_token=$json['access_token'];
        }else{
            $this->error("授权失败," . $result['msg']);
        }
        $access_token=$json['access_token'];
        //获取客户列表
      $userList=  $this->user->select();
        $datas=[];
        $customeruserdata=[];
        foreach ($userList as $k=>$v){
            $customeruseridListurl="https://qyapi.weixin.qq.com/cgi-bin/externalcontact/list?access_token=".$access_token."&userid=".$v['userid'];//.$this->auth->userid;
            $customeruseridList=  (array)json_decode($this->request($customeruseridListurl,[]), true); // 获得用户userid
            //批量获取客户详情
           // $customeruseridList['external_userid'];


            foreach ($customeruseridList['external_userid'] as $key=>$value){
                $customeruserdetailsurl="https://qyapi.weixin.qq.com/cgi-bin/externalcontact/get?access_token=".$access_token."&external_userid=".$value;
                $customeruserdetails= (array)json_decode($this->request($customeruserdetailsurl,[]), true);

                if(!$this->CustomerCustomers->where(['external_userid'=>$customeruserdetails['external_contact']['external_userid']])->find() &&
                    !in_array($customeruserdetails['external_contact']['external_userid'],$customeruserdata)){
                    $data['external_userid']=$customeruserdetails['external_contact']['external_userid'];
                    $data['name']=$customeruserdetails['external_contact']['name'];
                    $data['avatar']=$customeruserdetails['external_contact']['avatar'];
                    $data['type']=$customeruserdetails['external_contact']['type'];
                    $data['gender']=$customeruserdetails['external_contact']['gender'];

                    if($data['type']==2){
                        $data['corp_name']=$customeruserdetails['external_contact']['corp_name'];
                        $data['corp_full_name']=$customeruserdetails['external_contact']['corp_full_name'];
                    }

                    $data['follow_userid']=implode(",",array_column($customeruserdetails['follow_user'],'userid'));
                    $datas[]=$data;
                    $customeruserdata[]=$customeruserdetails['external_contact']['external_userid'];
                }


            }
        }


        if(!empty($datas)){
            $this->CustomerCustomers->saveAll($datas);
        }
        $this->success('更新完毕');

    }




    /**获取部门列表--定时任务
     * @param $url
     * @param $params
     * @return bool|string
     */
        public function departmentList(){
            $result=getaccess_token();
            if ($result['ret']) {
                $json = (array)json_decode($result['msg'], true);
                $access_token=$json['access_token'];
            }else{
                $this->error("授权失败," . $result['msg']);
            }
            $access_token=$json['access_token'];
            //获取客户列表
            $departmentListurl="https://qyapi.weixin.qq.com/cgi-bin/department/list?access_token=".$access_token;//.$this->auth->userid;
            $departmentList=  (array)json_decode($this->request($departmentListurl,[]), true); // 获得部门
            $alldata=[];

            foreach ($departmentList['department'] as $key=>$value){
              if(!$this->department->get(['department_id'=>$value['id']])){
                 $data=['department_id'=>$value['id'],'name'=>$value['name'],'parentid'=>$value['parentid'],'order'=>$value['order']];
                  $alldata[]=$data;
              }

             }
            if(!empty($alldata)){
                $this->department->saveAll($alldata);
            }
            $this->success('部门更新成功');
        }

    /**
     * 更新企业微信成员
     */
    public function userList(){
        $result=getaccess_token();
        if ($result['ret']) {
            $json = (array)json_decode($result['msg'], true);
            $access_token=$json['access_token'];
        }else{
            $this->error("授权失败," . $result['msg']);
        }
       $department= $this->department->select();
        $access_token=$json['access_token'];
        $dataall=[];
        foreach ($department as $key=>$value){
            $userListurl="https://qyapi.weixin.qq.com/cgi-bin/user/list?access_token=".$access_token."&department_id=".$value['department_id'];//.$this->auth->userid;
            $useridList=  (array)json_decode($this->request($userListurl,[]), true); // 获得用户userid

         // dump($useridList);
            if(!empty($userlist= $useridList['userlist'])){
                foreach ($useridList['userlist'] as $k=>$v){
                    if($this->user->get(['userid'=>$v['userid']])){ //用户不存在获得用户的信息在存数据库
                      $data=['username'=>$v['name'],'userid'=>$v['userid'],'department_ids'=>implode(",",
                          $v['department']),
                          'position'=>$v['position'],'is_leader_in_dept'=>implode(",",$v['is_leader_in_dept']),'direct_leader'=>implode(",",$v['direct_leader'])];
                        $this->user->where('userid',$v['userid'])->update($data);
                    }else{
                        $data=['username'=>$v['name'],'userid'=>$v['userid'],'department_ids'=>implode(",",
                            $v['department']),'avatar'=>'https://'.$_SERVER['HTTP_HOST'].'/assets/img/user.png',
                            'position'=>$v['position'],'is_leader_in_dept'=>implode(",",$v['is_leader_in_dept']),'direct_leader'=>implode(",",$v['direct_leader'])];
                        $this->user->save($data);
                    }
                }
            }
        }

       $this->success('OK');
    }




    public  function request($url, $params)
    {
        $ch = curl_init();

//$this_header = array("content-type: application/x-www-form-urlencoded;charset=UTF-8");

        $this_header = array('Content-Type: application/json; charset=utf-8');

        curl_setopt($ch, CURLOPT_HTTPHEADER, $this_header);

        curl_setopt($ch, CURLOPT_URL, $url);

        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);

        curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (compatible; MSIE 5.01; Windows NT 5.0)');

        curl_setopt($ch, CURLOPT_TIMEOUT, 30);

        curl_setopt($ch, CURLOPT_POST, 1);

        curl_setopt($ch, CURLOPT_POSTFIELDS, $params);

        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);//如果不加验证,就设false,商户自行处理

        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);

        $output = curl_exec($ch);
        curl_close($ch);

        return $output;
    }


}
